import { defineStore } from "pinia";
import { IUserState } from "./types";
import { userLogin, refreshUserInfo } from "@/api/user/user";
import pinia from "@/store";
export const useUserStore = defineStore("user", {
  state: (): IUserState => ({
    username: "admin",
    accessToken: "",
    refreshToken: "",
    roles: ["common"],
  }),
  getters: {},
  actions: {
    storeUserLogin(data) {
       return userLogin(data).then(res => {
            this.username = res.username
            this.accessToken = res.accessToken
            // this.refreshToken = res.refreshToken
            this.roles = res.roles
            return res
        })
    },
    refreshUserInfo() {
       if(this.username == 'admin' && this.accessToken != '') {
          refreshUserInfo({
            accessToken: this.accessToken,
          }).then(res=>{
            this.username = res.username
            this.accessToken = res.accessToken
            // this.refreshToken = res.refreshToken
            this.roles = res.roles
          })
       }
    }
  },
  // 持久化保存 accessToken
  persist: {
    key: 'userInfo',
    storage: sessionStorage,
    paths: ['accessToken'],
  },
});
